<template>
  <a-card :bordered="false">
    <a-button size="small" type="primary" class="mb-5" @click="onAddMenu">添加菜单</a-button>
    <a-table
      v-if="data"
      size="small"
      rowKey="id"
      bordered
      :columns="columns"
      :data-source="data"
      :pagination="false"
      :loading="loading">
      <template slot="icon" slot-scope="text">
        <a-icon v-if="text" :type="text" />
      </template>
      <template slot="show" slot-scope="text">
        <a-tag :color="text?'green':'red'">
          {{ text?'是':'否' }}
        </a-tag>
      </template>
      <template slot="action" slot-scope="text, record">
        <a @click="onSubMenu(record)">添加子菜单</a>
        <a-divider type="vertical" />
        <a @click="onEdit(record)">编辑</a>
        <a-divider type="vertical" />
        <a @click="onDel(record)">删除</a>
      </template>
    </a-table>
    <a-modal
      title="添加菜单"
      :dialogStyle="{top:'10px'}"
      :visible="menuInfoModal"
      @cancel="menuInfoModal=false"
      :confirm-loading="confirmLoading"
      @ok="handleSubmit"
    >
      <a-form-model
        ref="ruleForm"
        layout="horizontal"
        :model="menuInfo"
        :rules="rules"
        :labelCol="{span:7}"
        :wrapperCol="{span:16}">
        <a-form-model-item label="菜单标识" prop="name">
          <a-input v-model="menuInfo.name" />
        </a-form-model-item>
        <a-form-model-item label="菜单名称" prop="meta.title">
          <a-input v-model="menuInfo.meta.title" />
        </a-form-model-item>
        <a-form-model-item label="菜单模板" prop="component">
          <a-select v-model="menuInfo.component">
            <a-select-option v-for="menu in menuComponents" :key="menu" :value="menu">{{ menu }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="图标" prop="meta.icon">
          <a-input v-model="menuInfo.meta.icon" />
        </a-form-model-item>
        <a-form-model-item label="排序" prop="sort">
          <a-input-number v-model="menuInfo.sort" :min="0" style="width: 100%"/>
        </a-form-model-item>
        <a-form-model-item label="是否显示在导航栏" prop="show">
          <a-radio-group name="radioGroup" v-model="menuInfo.meta.show">
            <a-radio :value="true">是</a-radio>
            <a-radio :value="false">否</a-radio>
          </a-radio-group>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </a-card>
</template>

<script>
import { getAllRouterComponents } from '@/router/generator-routers'
import { getMenuTree, addMenu, editMenu, addSubMenu, deleteMenuById } from '@/api/menus'
import { formatMenus } from '@/utils/common'

const columns = [
  {
    title: '菜单名称',
    dataIndex: 'meta.title',
    key: 'meta.title'
  },
  {
    title: '标识',
    align: 'center',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '菜单模板',
    align: 'center',
    dataIndex: 'component',
    key: 'component'
  },
  {
    title: '图标',
    align: 'center',
    dataIndex: 'meta.icon',
    width: '80px',
    scopedSlots: { customRender: 'icon' }
  },
  {
    title: '排序',
    align: 'center',
    dataIndex: 'sort',
    width: '80px'
  },
  {
    title: '是否显示在导航栏',
    align: 'center',
    dataIndex: 'meta.show',
    width: '100px',
    scopedSlots: { customRender: 'show' }
  },
  {
    title: '操作',
    align: 'center',
    dataIndex: 'action',
    width: '200px',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'MenuList',
  data () {
    return {
      data: [],
      loading: false,
      columns: columns,

      menuInfo: {
        name: '',
        meta: {
          title: '',
          icon: '',
          show: true
        },
        component: '',
        parentId: 0,
        sort: 0
      },
      // 是否为添加子菜单
      isSubAdd: false,
      rules: {
        name: [
          { required: true, message: '请输入唯一标识', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (['BasicLayout', 'BlankLayout', 'RouteView', 'PageView', '403', '404', '500'].includes(value.trim())) {
                callback(new Error('此为公共模板标识，请输入唯一标识'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        'meta.title': [
          { required: true, message: '请输入菜单名称', trigger: 'blur' }
        ],
        component: [
          { required: true, message: '请输入菜单模板', trigger: 'blur' }
        ]
      },
      menuInfoModal: false,
      confirmLoading: false,
      menuComponents: []
    }
  },
  created () {
    this.menuComponents = getAllRouterComponents()
  },
  mounted () {
    this.getList()
  },
  methods: {
    getList () {
      this.loading = true
      getMenuTree().then(response => {
        this.data = formatMenus(response.data)
      }).finally(() => {
        this.loading = false
      })
    },
    handleSubmit () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          const info = { ...this.menuInfo }
          delete info.children
          if (info.id) {
            editMenu(info).then(() => {
              this.$message.success('编辑菜单成功')
              this.menuInfoModal = false
              this.getList()
            }).finally(() => {
              this.confirmLoading = false
            })
          } else {
            if (this.isSubAdd) {
              addSubMenu(info, info.parentId).then(() => {
                this.$message.success('添加菜单成功')
                this.menuInfoModal = false
                this.getList()
              }).finally(() => {
                this.confirmLoading = false
              })
            } else {
              addMenu(info).then(() => {
                this.$message.success('添加菜单成功')
                this.menuInfoModal = false
                this.getList()
              }).finally(() => {
                this.confirmLoading = false
              })
            }
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 添加菜单、初始化数据
    onAddMenu () {
      this.isSubAdd = false
      this.menuInfo = {
        name: '',
        meta: {
          title: '',
          icon: '',
          show: true
        },
        component: '',
        parentId: 0,
        sort: 0
      }
      this.menuInfoModal = true
    },
    // 添加子菜单
    onSubMenu (record) {
      this.isSubAdd = true
      this.menuInfo = {
        name: '',
        meta: {
          title: '',
          icon: '',
          show: true
        },
        component: '',
        parentId: record.id,
        sort: 0
      }
      this.menuInfoModal = true
    },
    onEdit (record) {
      this.menuInfo = JSON.parse(JSON.stringify(record))
      this.menuInfoModal = true
    },
    onDel (record) {
      const that = this
      this.$confirm({
        title: '系统提示',
        content: `确定删除${record.meta.title}吗？`,
        onOk () {
          deleteMenuById(record.id).then(() => {
            that.$message.success('删除成功')
            that.getList()
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
